package com.dmyang.service.impl;

import com.dmyang.common.pojo.BootstrapTableResult;
import com.dmyang.common.pojo.HyResult;
import com.dmyang.dao.HyCategoryMapper;
import com.dmyang.entity.HyCategory;
import com.dmyang.entity.HyCategoryExample;
import com.dmyang.service.CategoryService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 分类管理Service
 * Created by brss on 2017/8/2.
 */
@Service("categoryServiceImpl")
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private HyCategoryMapper categoryMapper;

    /**
     * 列出所有的分类（分页）
     * @param offset 从第多少条开始显示
     * @param limit 每页显示的条数
     * @return 要求格式的对象
     */
    @Transactional
    @Override
    public BootstrapTableResult showCategoryList(Integer offset, Integer limit) {
        HyCategoryExample example = new HyCategoryExample();
        PageHelper.startPage(offset/limit+1,limit);
        List<HyCategory> list = categoryMapper.selectByExample(example);
        PageInfo<HyCategory> info = new PageInfo<>(list);
        BootstrapTableResult result = new BootstrapTableResult(info.getTotal(), list);
        return result;
    }

    /**
     * 插入一条新的分类
     * @param category
     * @return
     * @throws Exception
     */
    @Transactional
    @Override
    public HyResult addCategory(HyCategory category) throws Exception {
        int i = categoryMapper.insertSelective(category);
        if(i>0){
            return HyResult.build(200,"插入成功!");
        }
        return HyResult.build(500,"插入失败!");
    }

    /**
     * 修改一条分类
     * @param category
     * @return
     * @throws Exception
     */
    @Transactional
    @Override
    public HyResult modifyCategory(HyCategory category) throws Exception {
        categoryMapper.updateByPrimaryKeySelective(category);
        return HyResult.build(200,"修改成功!");
    }

    /**
     * 删除分类（多条数据用，隔开）
     * @param ids
     * @return
     * @throws Exception
     */
    @Transactional
    @Override
    public HyResult deleteCategory(String ids) throws Exception {
        HyResult result = null;
        if(ids.contains(",")){
            //多条数据
            String[] idStr = ids.split(",");
            for(String id : idStr){
                categoryMapper.deleteByPrimaryKey(Integer.parseInt(id));
            }
            result = HyResult.build(200,"删除成功");
        }else {
            //单条数据
            categoryMapper.deleteByPrimaryKey(Integer.parseInt(ids));
            result = HyResult.build(200,"删除成功");
        }
        return result;
    }

    @Override
    public List<HyCategory> showAllCategory() {
        HyCategoryExample example = new HyCategoryExample();
        List<HyCategory> list = categoryMapper.selectByExample(example);
        return list;
    }


}
